package com.ilxqx.framework.system.controller;

import com.google.common.collect.Lists;
import com.ilxqx.framework.system.controller.base.AbstractFrameworkController;
import com.ilxqx.framework.system.entity.SysMenu;
import com.ilxqx.framework.system.form.search.SysMenuSearchForm;
import com.ilxqx.framework.system.form.update.SysMenuUpdateForm;
import com.ilxqx.framework.system.service.SysMenuService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统菜单控制器
 * @author venus
 */
@Api("系统菜单控制器")
@RestController
@RequestMapping("/sys/sys-menu")
@Slf4j
public class SysMenuController extends AbstractFrameworkController<SysMenu, Long, SysMenuSearchForm, SysMenuUpdateForm> {

	private final SysMenuService sysMenuService;

	@Autowired
	public SysMenuController(SysMenuService sysMenuService) {
		super(sysMenuService);
		this.sysMenuService = sysMenuService;
	}

	/**
	 * 是否自定义数据获取
	 *
	 * @return bool
	 */
	@Override
	public boolean isCustomGetListData() {
		return true;
	}

	/**
	 * 自定义list数据获取
	 *
	 * @return 数据
	 */
	@Override
	public Object customGetListData() {
		List<SysMenu> sysMenuList = this.sysMenuService.getListByParentMenuId(0L);
		return this.flatMenus(sysMenuList, 0);
	}

	/**
	 * 将子元素进行扁平化
	 * @param sysMenuList 菜单列表
	 * @return 菜单列表
	 */
	private List<SysMenu> flatMenus(List<SysMenu> sysMenuList, int level) {
		return sysMenuList
			.stream()
			.map(sysMenu -> {
				String title = StringUtils.repeat('+', level) + " " + sysMenu.getMeta().getTitle();
				sysMenu.getMeta().setTitle(title.trim());
				if (sysMenu.getChildren() != null && sysMenu.getChildren().size() > 0) {
					List<SysMenu> children = sysMenu.getChildren();
					children.sort(Comparator.comparingInt(SysMenu::getSequence));
					sysMenu.setChildren(null);
					List<SysMenu> flatList = Lists.newArrayList(sysMenu);
					flatList.addAll(this.flatMenus(children, level + 1));
					return flatList;
				}
				return Lists.newArrayList(sysMenu);
			})
			.flatMap(Collection::stream)
			.collect(Collectors.toList());
	}

	/**
	 * 在实体创建之前处理实体属性数据
	 *
	 * @param entity 实体对象
	 * @param form   表单对象
	 */
	@Override
	public void beforeAdd(SysMenu entity, SysMenuUpdateForm form) {
		BeanUtils.copyProperties(form, entity.getMeta());
	}

	/**
	 * 在实体修改之前处理实体属性数据
	 *
	 * @param entity 实体对象
	 * @param form   表单对象
	 */
	@Override
	public void beforeModify(SysMenu entity, SysMenuUpdateForm form) {
		BeanUtils.copyProperties(form, entity.getMeta());
	}

}

